package ray.mgocc.parser;

import java.io.IOException;
import java.io.StringReader;
import java.io.BufferedReader;
import java.io.Reader;
import java.io.Writer;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.File;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.io.FileFilter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @deprecated 元のhtmlに問題があるので。{@link HtmlParser}を使用のこと。
 */
public class Converter{
    private final static Log log = LogFactory.getLog(Converter.class);
    private final static String SEPARATOR = "\r\n";
    public Converter(){
    }
    private void convertDir(File dir){
        FileFilter filter = new FileFilter(){
                public boolean accept(File file){
                    return file.getName().matches(".*\\.html$");
                }
            };
        for(File in:dir.listFiles(filter)){
            convert(in);
        }
    }
    private void convertFile(File in){
        String name = in.getName();
        name = name.replaceAll("\\.html$","");
        name += ".xhtml";

        File out = new File(in.getParent(),name);
        convert(in,out);
    }
    public void convert(File in){
        if(in.isDirectory()){
            convertDir(in);
        }else{
            convertFile(in);
        }
    }
    public void convert(File in,File out){
        if(out.exists()){
            log.info("exists "+out.toURI());
            return;
        }
        log.info("convert:"+in.getName()+" -> "+out.getName());

        Reader r = null;
        Writer w = null;
        try{
            r = new FileReader(in);
            w = new FileWriter(out);
            parse(r,w);
            w.flush();
        }catch(IOException e){
            log.error("can not use temp file.",e);
        }finally{
            try{
                if(null!=w){
                    w.close();
                    w = null;
                }
                if(null!=r){
                    r.close();
                    r = null;
                }
            }catch(IOException e){
                log.error("can not close.",e);
            }
        }
    }
    public void parse(Reader source,Writer out){
        BufferedReader in = new BufferedReader(source);

        boolean isBody = false;
        Pattern startBody = Pattern.compile(".*<body>.*");
        boolean isForm = false;
        Pattern startForm = Pattern.compile(".*<form.*");
        Pattern endForm = Pattern.compile(".*</form>.*");
        Pattern wbr = Pattern.compile(".*(<wbr>).*");
        Pattern img = Pattern.compile(".*(<img[^>].*>).*");
        String line = null;
        try{
            while(null!=(line=in.readLine())){
                Matcher matcher;
                if(startBody.matcher(line).matches()){
                    //headerを追加する。
                    isBody = true;
                    out.write(getXhtmlHeader());
                }

                line = wbr.matcher(line).replaceAll("");
                line = img.matcher(line).replaceAll("");
                // formは省く。
                if(startForm.matcher(line).matches()){
                    isForm = true;
                }
                if(endForm.matcher(line).matches()){
                    isForm = false;
                }
                if(isBody && !isForm){
                    out.write(line);
                    out.write(SEPARATOR);
                }
            }
        }catch(IOException e){
            log.error("can not parse.",e);
        }
    }
    private static String getXhtmlHeader(){
        StringBuffer b = new StringBuffer();
        b.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append(SEPARATOR);
        b.append("<?xml-stylesheet href=\"./html.css\" type=\"text/css\"?>").append(SEPARATOR);
        //b.append("<!DOCTYPE html").append(SEPARATOR);
        //b.append("   PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"").append(SEPARATOR);
        //        b.append("   \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">").append(SEPARATOR);
        b.append("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"ja\" lang=\"ja\">").append(SEPARATOR);
        b.append("  <head>").append(SEPARATOR);
        b.append("    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />").append(SEPARATOR);
        b.append("    <title>template</title>").append(SEPARATOR);
        b.append("    <link rel=\"stylesheet\" type=\"text/css\" href=\"./html.css\" />").append(SEPARATOR);
        b.append("  </head>").append(SEPARATOR);
        return b.toString();
    }
}
